import { createStore,applyMiddleware } from "redux";
import Thunk from 'redux-thunk'

//1.定义action创建函数
function collect_action(item) {
    return {
        type: 'COLLECT',
        item
    }
}
function cancel_collect_action(id) {
    return {
        type: 'CANCEL_COLLECT',
        id
    }
}
function check_action(id) {
    return {
        type: 'CHECK',
        id
    }
}
function allcheck_action() {
    return {
        type: 'ALLCHECK'
    }
}

var data = {
    allchecked: false,//控制全选状态
    collectList:[]//保存所有收藏的 商品
}

//2.定义reducer
//作用: 根据action的类型, 修改state数据
//三必须: state必须有初始值,state必须深拷贝,switch必须有default分支
function reducer(state = data, action)
{
    state = localStorage.getItem('state') ? JSON.parse(localStorage.getItem('state')) : state;
    
    //深拷贝
    state = JSON.parse(JSON.stringify(state));

    switch (action.type)
    {
        case 'COLLECT'://收藏 动作
            //给将要收藏的商品对象 添加一个新的属性(checked)
            action.item.checked = false; 
            state.collectList.push(action.item);

            localStorage.setItem('state', JSON.stringify(state));
            
            return state;
        
        case 'CANCEL_COLLECT'://取消收藏 动作
            //先查找 对应id的商品在 收藏数据中的位置
            var findIndex = state.collectList.findIndex((item) => { return action.id === item.id });
            if (findIndex !== -1) {
                state.collectList.splice(findIndex, 1);
            }
            localStorage.setItem('state', JSON.stringify(state));
            return state;


        case 'CHECK'://单选 动作
            //先查找 对应id的商品在 收藏数据中的位置
            var findItem = state.collectList.find((item) => { return action.id === item.id });
            if (findItem) {
                findItem.checked = !findItem.checked;
            }
            //维护全选的状态
            state.allchecked = state.collectList.every((item) => {
                return item.checked;
            });
            
            localStorage.setItem('state', JSON.stringify(state));
            return state;

        case 'ALLCHECK'://全选 动作
            //更改全选的状态
            state.allchecked = !state.allchecked;
            //让所有商品的勾选状态和 全选状态保持一致
            state.collectList.forEach((item) => {
                item.checked = state.allchecked;
            })
            localStorage.setItem('state', JSON.stringify(state));
            return state;

        default:
            return state;    
    }
}

//3.创建store
var store = createStore(reducer, applyMiddleware(Thunk));

//导出
export {
    store,
    collect_action,
    cancel_collect_action,
    check_action,
    allcheck_action
}